package com.cxrj.zhsq.utils;

import java.time.LocalDate;

public class AgeUtil {

    //根据身份证获取年龄
    public static int getAgeByIDCard(String idCard){

        String birth = idCard.substring(6,14);
        int birthYear = Integer.valueOf(birth.substring(0,4));
        int birthMonth = Integer.valueOf(birth.substring(4,6));
        int birthDay = Integer.valueOf(birth.substring(6));

        int nYear = LocalDate.now().getYear();
        int nMonth = LocalDate.now().getMonthValue();
        int nDay = LocalDate.now().getDayOfMonth();

        int age;

        if (nMonth > birthMonth){
            age = nYear - birthYear;
        } else if (nMonth < birthMonth){
            age = nYear - birthYear - 1;
        } else{
            if (nDay > birthDay){
                age = nYear - birthYear;
            } else {
                age = nYear - birthYear - 1;
            }
        }
        return age;
    }

    public static void main(String[] args){

        System.err.println(getAgeByIDCard("420104199408280422"));
    }
}
